package main

import (
	"basic-go/src/go-routine/util"
	"fmt"
	"strconv"
)

// 启动一个协程，将1-2000放入一个channel中
// 启动8个协程，从该channel读取整数，并计算1+...+n的值，将其放入另一个channel中
// 最后8个协程完成工作后，再遍历结果channel，显示结果

type computeResult struct {
	n      int
	result int
}

// 格式化输出
func (r *computeResult) String() string {
	return strconv.Itoa(r.n) + " -> " + strconv.Itoa(r.result)
}

var countDownLatch *util.CountDownLatch

func putNumber(intChan chan<- int, count int) {
	for i := 1; i <= count; i++ {
		intChan <- i
		// time.Sleep(time.Second)
	}
	close(intChan)
	countDownLatch.CountDown()
}

func compute(intChan <-chan int, resultChan chan<- *computeResult) {
	for num := range intChan {
		var result = 0
		for i := 1; i <= num; i++ {
			result += i
		}
		resultChan <- &computeResult{num, result}
	}
	countDownLatch.CountDown()
}

func main() {

	var intChan = make(chan int, 1000)
	var resultChan = make(chan *computeResult, 2000)

	countDownLatch = util.NewCountDownLatch(9)

	go putNumber(intChan, 2000)

	for i := 1; i <= 8; i++ {
		go compute(intChan, resultChan)
	}

	// 异步关闭resultChan
	go func() {
		countDownLatch.Await()
		close(resultChan)
	}()

	for res := range resultChan {
		fmt.Println("res =", res)
	}
}
